<?php

namespace App\Http\Controllers\Admin\User;

use App\Http\Controllers\Admin\BaseAdminController;
use App\Models\Messages;
use App\Models\UploadedFile;
use App\Models\Users;
use App\Models\Earns;
use App\Models\UsersBind;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;

/**
 * 用户控制器
 *
 * @author lxp
 * @package App\Http\Controllers\User
 */
class UsersController extends BaseAdminController
{

    public function __construct()
    {
        parent::__construct();
    }

    /**
     * 用户列表
     *
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     * @author lxp 20170111
     */
    public function index()
    {
        // 处理排序
        $sort = request('sort', 'uid');
        $order = request('order', 'desc');

        $query = Users::orderBy($sort, $order);
        // 筛选用户名
        if (request('username')) {
            if (is_email(request('username'))) {
                $query->where('email', request('username'));
            } elseif (is_mobile(request('username'))) {
                $query->where('phone', request('username'));
            } else {
                $query->where('username', 'LIKE', "%" . request('username') . "%");
            }
        }
        // 筛选注册时间
        if (request('created_at')) {
            list($begin, $end) = explode(' - ', request('created_at'));
            $query->whereBetween('created_at', [
                date('Y-m-d H:i:s', strtotime($begin)),
                date('Y-m-d H:i:s', strtotime('+1 day', strtotime($end)))
            ]);
        }
        // 取得列表
        $users = $query->select([
            'uid',
            'nickname',
            'openid',
            'avatar',
            'created_at',
            'updated_at',
            'lastloginip',
            'money',
            'status'
        ])->paginate(parent::PERPAGE);
        // 将查询参数拼接到分页链接中
        $users->appends(app('request')->all());

        return view('admin.user.users', [
            'users' => $users,
        ]);

    }

    /**
     * 用户佣金明细列表
     *
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     * @author yh 20201225
     */
    public function earn($uid)
    {
        // 处理排序
        $sort = request('sort', 'id');
        $order = request('order', 'desc');
        $openid = User::where('uid',$uid)->first();
        $query = Earns::orderBy($sort, $order)->where('openid',$openid);
        // 筛选用户名
        if (request('title')) {
            $query->where('title', 'LIKE', "%" . request('title') . "%");
        }
        // 筛选注册时间
        if (request('created_at')) {
            list($begin, $end) = explode(' - ', request('created_at'));
            $query->whereBetween('created_at', [
                date('Y-m-d H:i:s', strtotime($begin)),
                date('Y-m-d H:i:s', strtotime('+1 day', strtotime($end)))
            ]);
        }
        // 取得列表
        $users = $query->select([
            'id',
            'nickname',
            'openid',
            'avatar',
            'created_at',
            'updated_at',
            'money',
            'invitor_nickname',
            'nivitor_avatar',
            'status'
        ])->paginate(parent::PERPAGE);
        // 将查询参数拼接到分页链接中
        $users->appends(app('request')->all());

        return view('admin.user.earns', [
            'users' => $users,
            'id' =>$id
        ]);
        
    }
    /**
     * 添加用户
     *
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     * @author lxp 20170825
     */
    public function add()
    {
        return view('admin.user.users_form');
    }

    /**
     * 编辑用户
     *
     * @param $uid
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     * @author lxp 20170111
     */
    public function edit($uid)
    {
        // 取得用户信息
        $user = Users::findOrFail($uid);

        return view('admin.user.users_form', [
            'user' => $user
        ]);
    }

    /**
     * 保存用户
     *
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     * @author lxp 20170206
     */
    public function save()
    {
        // 验证
        $rule = [
            'phone' => 'required|mobile|unique:users,phone,' . request('uid') . ',uid',
            'nickname' => 'required|unique:users,nickname,' . request('uid') . ',uid'
        ];
        if (!request('uid')) {
            $rule = array_merge([
                'username' => 'required|unique:users,username,' . request('uid') . ',uid',
                'password' => 'required|min:6'
            ], $rule);
        } else {
            $rule = array_merge([
                'password' => 'nullable|min:6'
            ], $rule);
        }
        $this->validate(request(), $rule, [], [
            'nickname' => '昵称'
        ]);

        // 保存用户信息
        DB::transaction(function () {
            $user = Users::findOrNew(request('uid'));
            if (!request('uid')) {
                $user->username = request('username');
            } else {
                // 屏蔽 timestamps，阻止时间戳自动更新
                $user->timestamps = false;
            }
            $user->nickname = request('nickname');
            $user->email = request('email');
            $user->phone = request('phone');
            if (request()->filled('password')) {
                // 处理密码
                $user->salt = Str::random(6);
                $user->password = get_password(request('password'), $user->salt);
            }
            $user->avatar = request('avatar');
            $user->is_test = request('is_test', 0);
            $user->save();

            // 更新附件id
            if (!request('uid')) {
                // 更新头像
                if (intval(request('avatar_file_id'))) {
                    UploadedFile::where('file_id', intval(request('avatar_file_id')))->update(['item_id' => $user->uid]);
                }
            }
        });

        return $this->success(get_session_url('index'));
    }

    /**
     * 删除用户
     *
     * @param int $uid
     * @return \Illuminate\Http\JsonResponse
     * @author lxp 20160713
     */
    public function delete($uid)
    {
        if (request()->ajax() && intval($uid)) {
            // 判断用户是否可以被删除

            // 删除用户
            Users::destroy($uid);
            // 删除第三方登录信息
            UsersBind::where('uid', $uid)->delete();
            Messages::where('uid',$uid)->delete();
            Messages::where('fid',$uid)->delete();
            return $this->success();
        }
    }

    /**
     * 禁用用户
     *
     * @param int $uid
     * @return \Illuminate\Http\JsonResponse
     * @author yh 20200411
     */
    public function change($uid)
    {
        if (request()->ajax() && intval($uid)) {
            // 判断用户是否可以被删除

            // 删除用户
            $users = Users::where('uid', $uid)->first();
            if ($users->status == 1) {
                $users->status = 0;
                //禁用用户时，清除用户登录状态
                $users->api_token = null;
            } else {
                $users->status = 1;
            }
            $users->save();
        }
        return $this->success();
    }
    /**
     * 重置用户密码
     *
     * @param int $uid
     * @return \Illuminate\Http\JsonResponse
     * @author yh 20200411
     */
    public function resetPwd($uid)
    {
        $users = Users::where('uid', $uid)->first();
        $salt = Str::random(6);
        $users->salt = $salt;
        $users->password = get_password('111111', $salt);
        $users->save();
        return $this->success();
    }
    /**
     * 禁用用户论坛功能
     *
     * @param int $uid
     * @return \Illuminate\Http\JsonResponse
     * @author yh 20200411
     */
    public function comment($uid)
    {
        $users = Users::where('uid', $uid)->first();
        if ($users->allow_comment == '1') {
            $users->allow_comment = 0;
        } else {
            $users->allow_comment = 1;
        }
        $users->save();
        return $this->success();
    }
}